package com.wzb.mybatisplus.bitaction.electrumaction.five;

import org.bitcoinj.core.*;
import org.bitcoinj.params.MainNetParams;

import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;

public class Batch5KeyGeneratorFixed {

    private static final NetworkParameters params = MainNetParams.get();
    private static final SecureRandom secureRandom = new SecureRandom();

    public static void main(String[] args) {
        System.out.println("批量生成以5开头的比特币私钥 - 修复版");
        System.out.println("bitcoinj-core 0.16.2");
        System.out.println("=========================================\n");

        generateMultipleKeys(5);
    }

    public static void generateMultipleKeys(int count) {
        Instant start = Instant.now();
        int totalAttempts = 0;
        int keysFound = 0;

        System.out.println("开始生成 " + count + " 个以5开头的私钥...");

        for (int i = 1; i <= count; i++) {
            int keyAttempts = 0;
            ECKey foundKey = null;

            while (foundKey == null) {
                keyAttempts++;
                totalAttempts++;

                ECKey key = new ECKey(secureRandom);
                String privateKeyWIF = key.getPrivateKeyAsWiF(params);

                if (privateKeyWIF.startsWith("5")) {
                    foundKey = key;
                    keysFound++;

                    System.out.println("\n--- 私钥 #" + keysFound + " ---");
                    printKeyWithAddress(foundKey, keyAttempts);
                }

                // 进度显示
                if (totalAttempts % 5000 == 0) {
                    System.out.printf("总进度: 尝试 %d 次, 找到 %d/%d 个\n",
                            totalAttempts, keysFound, count);
                }
            }
        }

        Instant end = Instant.now();
        Duration duration = Duration.between(start, end);

        // 打印统计
//        System.out.println("\n" + "=".repeat(50));
        System.out.println("生成完成!");
        System.out.println("总尝试次数: " + totalAttempts);
        System.out.println("成功生成: " + keysFound + " 个私钥");
        System.out.printf("成功率: %.4f%%\n", (keysFound * 100.0 / totalAttempts));
        System.out.println("总耗时: " + duration.toMillis() + " ms");
        System.out.printf("生成速度: %.2f 密钥/秒\n",
                (totalAttempts * 1000.0 / duration.toMillis()));
    }

    private static void printKeyWithAddress(ECKey key, int attempts) {
        String privateKeyWIF = key.getPrivateKeyAsWiF(params);
        String privateKeyHex = key.getPrivateKeyAsHex();

        // 修复：使用 LegacyAddress.fromKey 生成地址
        Address address = LegacyAddress.fromKey(params, key);

        System.out.println("尝试次数: " + attempts);
        System.out.println("私钥 (WIF): " + privateKeyWIF);
        System.out.println("私钥 (HEX): " + privateKeyHex);
        System.out.println("比特币地址: " + address.toString());
        System.out.println("是否压缩: " + key.isCompressed());
        System.out.println("格式: ✓ 主网未压缩 (5开头)");
    }
}
